package javacource.redis.lock;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Create by chenhd on 2021/10/23.
 */
@Component("redissionLock")
public class RedissionLock implements RedisLock, InitializingBean {

    private RedissonClient client;

    @Override
    public boolean lock(String key, String value, long second) {
        try {
            RLock lock = client.getLock("redissionLock");
            lock.lock(second, TimeUnit.SECONDS);
            return true;
        } catch (Exception e) {
            //log
        }
        return false;
    }

    @Override
    public boolean unLock(String key, String value) {
        try {
            RLock lock = client.getLock("redissionLock");
            lock.unlock();
            return true;
        } catch (Exception e) {
            //log
        }
        return false;
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        Config config = new Config();
        config.useSingleServer()
                .setAddress("redis://10.8.227.64:9852")
                .setPassword("jlmniuj34778@ggj#h2");
        client = Redisson.create(config);
    }
}
